#include "udpthreadworker.h"
#include "../osdglobal.h"
#include <QDebug>
#include <QUdpSocket>
#include <QStringList>

UDPThreadWorker::UDPThreadWorker(QObject *parent) :
    QObject(parent)
    ,m_socket(NULL)
{
}

UDPThreadWorker::~UDPThreadWorker()
{
    delete m_socket;
}


void UDPThreadWorker::sendMsg(QString method, QString msg)
{
    g_listen_mutex.lock();
    if (m_socket == NULL)
    {
        m_socket = new SocketSync(LOCAL_PORT);
    }

    disconnect(m_socket->udpsocket(),SIGNAL(readyRead()),this,SLOT(processPendingDatagram()));
    QString r = "";
    qDebug() << msg;
    int a = m_socket->sendUdpMessage(msg,REMOTE_IP,REMOTE_PORT,r);
    qDebug() << r << a;
    connect(m_socket->udpsocket(),SIGNAL(readyRead()),this,SLOT(processPendingDatagram()));
    emit response(method,r);

    g_listen_mutex.unlock();

    //
}

void UDPThreadWorker::processPendingDatagram()
{
    g_listen_mutex.lock();
    QString response;
    QStringList responseList;
    while(m_socket->udpsocket()->hasPendingDatagrams())
    {
        QByteArray datagram; //拥于存放接收的数据报
        datagram.resize(m_socket->udpsocket()->pendingDatagramSize());
        m_socket->udpsocket()->readDatagram(datagram.data(),datagram.size());
        response = datagram;
        qDebug("processPendingDatagram:%s", response.toStdString().c_str());
//        responseList = response.split("|");
//        if (responseList.size() < 2) {
//            continue;
//        }
        emit push(response);
    }
    g_listen_mutex.unlock();
}
